package com.ruitu.mall_98_2.order;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.beanu.arad.Arad;
import com.beanu.arad.base.PayResult;
import com.beanu.arad.base.my_base.Config;
import com.beanu.arad.base.my_base.MyBaseActivity;
import com.beanu.arad.utils.AppUtils;
import com.beanu.arad.utils.Logg;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.view.IdentifyingCode;
import com.beanu.arad.widget.dialog.CustomAlertDialog;
import com.beanu.arad.widget.progressactivity.ProgressLayout;
import com.ruitu.mall_98_2.R;
import com.ruitu.mall_98_2.dao.APIRetrofit;
import com.ruitu.mall_98_2.mvp.contract.PayOrderContract;
import com.ruitu.mall_98_2.mvp.model.PayOrderModel;
import com.ruitu.mall_98_2.mvp.presenter.PayOrderPresenter;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.api.BaseResult;
import com.ruitu.router_module.bean.api.SubscriberImpl;
import com.ruitu.router_module.bean.order.ConfirOrder;
import com.ruitu.router_module.bean.order.NeedPay;
import com.ruitu.router_module.bean.order.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class PayOrderActivity extends MyBaseActivity<PayOrderPresenter, PayOrderModel> implements PayOrderContract.View {
    private TextView tv_need_pay;
    private TextView tv_balance;
    private ConfirOrder confirOrder;
    private RelativeLayout rl_weixin_pay;
    private RelativeLayout rl_aili_pay;
    private RelativeLayout rl_yue_pay;
    private AlertDialog alertDialog;
    private TextView tv_get_code;
    private ImageView iv_verifactiion_code;
    private boolean isGeting = false;
    private int time = 60;

    private double orderTotal;//需要付款
    private IWXAPI iwxapi;
    private String data;
    private String needPay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_pay_order;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == rl_aili_pay) {
            showProgress();
            mPresenter.aliPayForApp("1", confirOrder.getId());
        }

        if (v == rl_yue_pay) {
            if (!TextUtils.isEmpty(data)) {
                if (orderTotal > Double.parseDouble(data)) {
                    ToastUtils.showShort("余额不足");
                } else {
                    showYuEPayDialog();
                }
            }

        }

        if (v == rl_weixin_pay) {
            if (AppUtils.isInstallApp("com.tencent.mm")) {
                showProgress();
                mPresenter.weixinPayForApp("0", confirOrder.getId());
            }else {
                ToastUtils.showShort("您没有安装微信");
            }
        }
    }

    @Override
    protected ProgressLayout findProgressLayout() {
        return null;
    }

    @Override
    protected void initViews() {
        super.initViews();
        setHeadTitle("收银台");
        if (!Arad.bus.isRegistered(this)) {
            Arad.bus.register(this);
        }
        iwxapi = WXAPIFactory.createWXAPI(this, Config.APP_ID, false);
        iwxapi.registerApp(Config.APP_ID);
        confirOrder = (ConfirOrder) getIntent().getSerializableExtra("confirOrder");
        tv_need_pay = findViewById(R.id.tv_need_pay);
        tv_balance = findViewById(R.id.tv_balance);
        rl_weixin_pay = findViewById(R.id.rl_weixin_pay);
        rl_aili_pay = findViewById(R.id.rl_aili_pay);
        rl_yue_pay = findViewById(R.id.rl_yue_pay);
        if (confirOrder != null) {
            showProgress();
            mPresenter.getOrderMoney(confirOrder.getId());
            orderTotal = confirOrder.getOrderTotal();
        }
        rl_aili_pay.setOnClickListener(this);
        rl_yue_pay.setOnClickListener(this);
        rl_weixin_pay.setOnClickListener(this);
    }

    @Override
    public void setPaySuc(final String info) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                PayTask payTask = new PayTask(PayOrderActivity.this);
                Map<String, String> map = payTask.payV2(info, true);
                Message message = new Message();
                message.what = 979;
                message.obj = map;
                handler.sendMessage(message);

            }
        }).start();
    }

    @Override
    public void setPaySuc() {
        paySuc();
    }

    private void paySuc() {
        if (TextUtils.equals(confirOrder.getOrderType(), "1") || TextUtils.equals("2", confirOrder.getOrderType())) {
            Bundle bundle = new Bundle();
            bundle.putSerializable("confirOrder", confirOrder);
            startActivity(AdvancePayResultActivity.class, bundle);
        } else {
            Bundle bundle = new Bundle();
            bundle.putSerializable("confirOrder", confirOrder);
            startActivity(PayResultActivity.class, bundle);
        }
        finish();
    }

    @Override
    public void setWeixinPay(PayReq payReq) {
        final com.tencent.mm.opensdk.modelpay.PayReq payReq1 = new com.tencent.mm.opensdk.modelpay.PayReq();
        String lon = System.currentTimeMillis() / 1000 + "";
        payReq1.appId = Config.APP_ID;
        Logg.i("APP_ID " + Config.APP_ID);
        payReq1.partnerId = payReq.getPartnerid();
        Logg.i("payReq.getPartnerId() " + payReq.getPartnerid());
        payReq1.prepayId = payReq.getPrepayid();
        Logg.i("payReq.getPrepayId() " + payReq.getPrepayid());
        payReq1.packageValue = "Sign=WXPay";
        payReq1.nonceStr = payReq.getNoncestr();
        Logg.i("payReq.getNonceStr() " + payReq.getNoncestr());
        payReq1.timeStamp = payReq.getTimestamp();
//        payReq1.timeStamp = lon;
        Logg.i("payReq.getTimeStamp() " + payReq.getTimestamp());
        payReq1.sign = payReq.getSign();
        Logg.i("payReq.getSign() " + payReq.getSign());
        iwxapi.sendReq(payReq1);
    }

    @Override
    public void setNeedPay(NeedPay needPay) {
        this.needPay = needPay.getPayMoney();
        confirOrder.setNeedPay(needPay.getPayMoney());
        tv_need_pay.setText(needPay.getPayMoney() + "元");
        getBalance();
    }

    //支付宝的
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 979:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String payStatus = payResult.getResultStatus();
                    if (TextUtils.equals(payStatus, "9000")) {// 判断resultStatus 为9000则代表支付成功
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtils.showShort("支付成功");
                        paySuc();

                    } else if (TextUtils.equals(payStatus, "6001")) {
                        ToastUtils.showShort("取消支付");
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtils.showShort("支付失败");
                    }
                    break;
                case 999:
                    if (isGeting) {
                        setGetCodeTime(--time);
                        handler.sendEmptyMessageDelayed(999, 1000);
                    }
                    break;

            }
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setPayResult(EventModel eventModel) {
        if (eventModel.getEventCode() == 18120500) {
            paySuc();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }

    private EditText et_code;

    private void showYuEPayDialog() {
        alertDialog = new AlertDialog.Builder(this).create();
        View view = View.inflate(this, R.layout.item_yue_pay_dialog, null);
        if (alertDialog != null) {
            alertDialog.setView(view);
        }
        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        TextView tv_cancle = view.findViewById(R.id.tv_cancle);
        tv_get_code = view.findViewById(R.id.tv_get_code);
        TextView tv_tel = view.findViewById(R.id.tv_tel);
        et_code = view.findViewById(R.id.et_code);
        final EditText et_iv_verifactiion_code = view.findViewById(R.id.et_iv_verifactiion_code);
        iv_verifactiion_code =view.findViewById(R.id.iv_verifactiion_code);
        getVerifactionCode();
        tv_tel.setText("验证码将发送到" + AppHolder.instance().getUser().getPhone().substring(0, 3) + "****" + AppHolder.instance().getUser().getPhone().substring(7, 11) + "请注意查收");
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = et_code.getText().toString();
                if (TextUtils.isEmpty(s)) {
                    ToastUtils.showShort("验证码不能为空");
                } else {
                    showProgress();
                    mPresenter.balanceForApp(AppHolder.instance().getUser().getAccountId(), s, confirOrder.getId());
                }
            }
        });
        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                stopHandler();
            }
        });

        tv_get_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.equals(et_iv_verifactiion_code.getText().toString().toLowerCase(), resultCode)) {
                    tv_get_code.setEnabled(false);
                    setGetCodeTime(60);
                    isGeting = true;
//                et_code.setText(baseResult.getData().toString());
                    handler.sendEmptyMessageDelayed(999, 1000);
                    getCode();
                } else {
                    ToastUtils.showShort("图片验证不正确");
                }
                getVerifactionCode();
            }
        });

        iv_verifactiion_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getVerifactionCode();
            }
        });

        alertDialog.show();

    }

    private String resultCode;

    private void getVerifactionCode() {
        iv_verifactiion_code.setImageBitmap(IdentifyingCode.getInstance().createBitmap());
        resultCode = IdentifyingCode.getInstance().getCode().toLowerCase();
    }

    private void stopHandler() {
        time = 60;
        handler.removeMessages(999);
    }

    private void getCode() {
        APIRetrofit.getDefault().smsSend(AppHolder.instance().getUser().getPhone(), "6")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SubscriberImpl<BaseResult>() {
                    @Override
                    public void onError(Throwable e) {
                        ToastUtils.showShort("获取验证码失败");
                    }

                    @Override
                    public void onNext(BaseResult baseResult) {
                        if (baseResult.isSuccess()) {
                            ToastUtils.showShort(baseResult.getMsg());

                        } else {
                            ToastUtils.showShort(baseResult.getMsg());
                        }
                    }
                });
    }

    private void getBalance() {
        APIRetrofit.getDefault().getBalance(AppHolder.instance().getUser().getAccountId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SubscriberImpl<BaseResult<String>>() {
                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(BaseResult<String> stringBaseResult) {
                        if (stringBaseResult.isSuccess()) {
                            data = stringBaseResult.getData();
                            setBalance();
                        }
                    }
                });
    }

    private void setBalance() {
        if (!TextUtils.isEmpty(data)) {
            if (Double.parseDouble(needPay.trim()) > Double.parseDouble(data)) {
                tv_balance.setText("余额不足");
            } else {
                tv_balance.setText("(" + data + "元)");
            }
        }
    }

    private void setGetCodeTime(int time) {
        if (time == 0) {
            isGeting = false;
            tv_get_code.setEnabled(true);
            tv_get_code.setText("获取验证码");
            this.time = 60;
        } else {
            tv_get_code.setText(time + "s后重新获取");
        }
    }

    CustomAlertDialog customAlertDialog;

    @Override
    public void onBackPressed() {
        customAlertDialog = new CustomAlertDialog(this, "订单还未支付,确定退出吗?", new CustomAlertDialog.OkOnClickListener() {
            @Override
            public void OkOnClick() {
                finish();
                customAlertDialog.dismiss();
            }
        });
        customAlertDialog.show();

    }
}
